<template>
  <div class="student_pre_register">
    <div class="spr_main">
      <div class="content">
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>学生姓名</div>
          </div>
          <div class="cont">
            <van-field v-model="params.studentName" placeholder="请输入学生姓名" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>学生性别</div>
          </div>
          <div class="cont">
            <van-field
              readonly
              clickable
              :value="params.genderText"
              placeholder="请选择学生性别"
              @click="showGenderPopup = true"
            />
            <van-popup v-model="showGenderPopup" round position="bottom">
              <van-picker
                show-toolbar
                :columns="genderOptions"
                @cancel="showGenderPopup = false"
                @confirm="onGenderConfirm"
              />
            </van-popup>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>出生日期</div>
          </div>
          <div class="cont">
            <van-field
              readonly
              clickable
              :value="params.birthDate"
              placeholder="请选择出生日期"
              @click="showDatePopup = true"
            />
            <van-popup v-model="showDatePopup" round position="bottom">
              <van-datetime-picker
                v-model="currentDate"
                type="date"
                title="选择出生日期"
                :min-date="minDate"
                :max-date="maxDate"
                @cancel="showDatePopup = false"
                @confirm="onDateConfirm"
              />
            </van-popup>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>联系电话</div>
          </div>
          <div class="cont">
            <van-field v-model="params.mobile" placeholder="请输入联系电话" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>所在学校</div>
          </div>
          <div class="cont">
            <van-field v-model="params.school" placeholder="请输入所在学校" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>家长姓名</div>
          </div>
          <div class="cont">
            <van-field v-model="params.parentName" placeholder="请输入家长姓名" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>家庭住址</div>
          </div>
          <div class="cont">
            <van-field v-model="params.address" placeholder="请输入家庭住址" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>培训校区</div>
          </div>
          <div class="cont">
            <van-field
              readonly
              clickable
              :value="params.campusText"
              placeholder="请选择培训校区"
              @click="showCampusPopup = true"
            />
            <van-popup v-model="showCampusPopup" round position="bottom">
              <van-picker
                show-toolbar
                :columns="campusOptions"
                @cancel="showCampusPopup = false"
                @confirm="onCampusConfirm"
              />
            </van-popup>
          </div>
        </div>
        <div class="bottom mainBgColor" @click="submit">提交预录信息</div>
      </div>
    </div>
  </div>
</template>

<script>
import { Field, Picker, Popup, DatetimePicker } from 'vant';
export default {
  components: {
    'van-field': Field,
    'van-picker': Picker,
    'van-popup': Popup,
    'van-datetime-picker': DatetimePicker
  },
  data() {
    return {
      showGenderPopup: false,
      showDatePopup: false,
      showCampusPopup: false,
      currentDate: new Date(),
      minDate: new Date(1990, 0, 1),
      maxDate: new Date(),
      genderOptions: [
        { text: '男', value: 0 },
        { text: '女', value: 1 }
      ],
      campusOptions: [],
      flag: true,
      params: {
        studentName: '',
        gender: null,
        genderText: '',
        birthDate: '',
        mobile: '',
        school: '',
        parentName: '',
        address: '',
        campus: null,
        campusText: ''
      }
    }
  },
  created() {
    // 初始化当前日期为10年前（假设学生年龄）
    const currentYear = new Date().getFullYear();
    this.currentDate = new Date(currentYear - 10, 0, 1);
    // 获取校区列表
    this.getCampusList();
  },
  beforeRouteEnter(to, from ,next) {
    next(async vm => {
      if (!window.localStorage.getItem('px_user_openid')) {
        try {
          let code = vm.getCode(to.path);
          if (!code) return
          let ret = await vm.$http.getUserIfRegister({code})
          localStorage.setItem('px_user_openid', ret.data.result.openId)
          // 保存完整的登录数据到缓存
          vm.$store.dispatch('saveLoginData', ret.data)
        } catch(err) {
          let code = vm.redirectGetCode(to.path);
          let ret = await vm.$http.getUserIfRegister({code})
          localStorage.setItem('px_user_openid', ret.data.result.openId)
          // 保存完整的登录数据到缓存
          vm.$store.dispatch('saveLoginData', ret.data)
        }
      }
    })
  },
  methods: {
    onGenderConfirm(value) {
      this.params.gender = value.value;
      this.params.genderText = value.text;
      this.showGenderPopup = false;
    },
    onDateConfirm(value) {
      const year = value.getFullYear();
      const month = value.getMonth() + 1;
      const day = value.getDate();
      this.params.birthDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
      this.showDatePopup = false;
    },
    onCampusConfirm(value) {
      this.params.campus = value.value;
      this.params.campusText = value.text;
      this.showCampusPopup = false;
    },
    // 获取校区列表
    async getCampusList() {
      try {
        const res = await this.$http.getCampusList();
        if (res.data && res.data.result) {
          // 将接口返回的校区数据转换为picker需要的格式
          this.campusOptions = res.data.result.map(item => ({
            text: item.deptName, // 接口返回的字段是deptName
            value: item.deptId   // 接口返回的字段是deptId
          }));
        }
      } catch (error) {
        console.error('获取校区列表失败:', error);
        this.$toast('获取校区列表失败，请重试');
      }
    },
    // 根据性别值获取性别文本
    getGenderText(gender) {
      const genderOption = this.genderOptions.find(option => option.value === gender);
      return genderOption ? genderOption.text : '';
    },
    async submit() {
      const { studentName, gender, birthDate, mobile, school, parentName, address, campus } = this.params;

      if (!studentName.length) return this.$toast('请输入学生姓名');
      if (gender === null || gender === '') return this.$toast('请选择性别');
      if (!birthDate.length) return this.$toast('请选择出生日期');
      if (!mobile.length) return this.$toast('请输入联系电话');
      if (!school.length) return this.$toast('请输入所在学校');
      if (!parentName.length) return this.$toast('请输入家长姓名');
      if (!address.length) return this.$toast('请输入家庭住址');
      if (campus === null || campus === '') return this.$toast('请选择校区');

      if (!this.flag) return;

      let openId = localStorage.getItem('px_user_openid');
      if (!openId) {
        this.$toast('正在获取openId...');
        let code = this.redirectGetCode(this.$route.path);
        let ret = await this.$http.getUserIfRegister({code});
        localStorage.setItem('px_user_openid', ret.data.result.openId);
        // 保存完整的登录数据到缓存
        this.$store.dispatch('saveLoginData', ret.data)
        this.flag = true;
        return;
      }

      const query = {
        studentName: studentName,
        studentSex: gender,
        studentBirthday: birthDate,
        studentAddress: address,
        studentMobile: mobile,
        parentName: parentName,
        atSchool: school,
        depId: campus,
        openId: openId
      };

    // 调用保存学生信息的API
    this.$http.saveStudentInfo(query).then(res => {
      this.flag = true;
      if (res.data && res.data.success) {
        // 提交成功，跳转到结果页面并传递返回的数据
        this.$router.push({
          name: 'studentPreRegisterResult',
          params: {
            resultData: res.data.result
          }
        });
      } else {
        // 提交失败，停留在当前页面并显示错误信息
        this.$toast(res.data.message || '提交失败，请重试');
      }
    }).catch(err => {
      this.flag = true;
      this.$toast(err.data.message || '提交失败，请重试');
    });
    },
    reset() {
      this.params = {
        studentName: '',
        gender: '',
        genderText: '',
        birthDate: '',
        mobile: '',
        school: '',
        parentName: '',
        address: '',
        campus: '',
        campusText: ''
      };
    }
  }
}
</script>

<style lang="scss" scoped>
.student_pre_register {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  color: #333;
  .spr_main {
    flex: 1;
    position: relative;
    background: rgba(241, 241, 249, 0.2);
    overflow: scroll;
    .content {
      width: 100%;
      position: relative;
      padding: 20px 20px 0px;
      box-sizing: border-box;
      border-radius: 4px;
      .info {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        .label {
          width: 70px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          .require {
            color: red;
            margin-right: 2px;
          }
        }
        .cont {
          background: #fff;
          margin-left: 5px;
          flex: 1;
          overflow: hidden;
          border: 1px solid rgba(222, 222, 222, .4);
          border-radius: 8px;
          position: relative;
          .van-cell::after {
            border: 0;
          }
          .ipt {
            width: 100%;
            height: 100%;
          }
        }
      }
      .bottom {
        width: 100%;
        height: 44px;
        margin-top: 80px;
        border-radius: 4px;
        color: #fff;
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
